
import 'package:shared_preferences/shared_preferences.dart';

class ValLocalStore {
  ///保存数据
  static Future<bool> saveValue(String key, dynamic value) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    if (value is int) {
      return await prefs.setInt(key, value);
    } else if (value is double) {
      return await prefs.setDouble(key, value);
    } else if (value is bool) {
      return await prefs.setBool(key, value);
    } else if (value is String) {
      return await prefs.setString(key, value);
    } else if (value is List) {
      return await prefs.setStringList(key, value as List<String>);
    } else {
      throw Exception("未知保存类型");
    }
  }

  ///读取数据
  static Future<T> getValue<T>(String key, T defaultValue) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    if (defaultValue is int) return (prefs.getInt(key) ?? defaultValue) as T;
    if (defaultValue is double) {
      return (prefs.getDouble(key) ?? defaultValue) as T;
    }
    if (defaultValue is bool) return (prefs.getBool(key) ?? defaultValue) as T;
    if (defaultValue is String) {
      return (prefs.getString(key) ?? defaultValue) as T;
    }
    if (defaultValue is List) {
      return (prefs.getStringList(key) ?? defaultValue) as T;
    }
    return defaultValue;
  }

  ///是否包含key
  static Future<bool> hasKey(String key) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return Future.value(prefs.containsKey(key));
  }

  ///删除
  static Future<bool> delete(String key) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return await prefs.remove(key);
  }
}